package conversation

import (
	"errors"
	"gim-server/apis/ws"
	"gim-server/consts"
	"gim-server/errs"
	"gim-server/model"
	"gim-server/sdk"
	"gim-server/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type DelConversationArgs struct {
	ConversationID int64 `json:"conversation_id"`
}

func delConversation(ctx *gin.Context) {
	var (
		err  error
		args = new(DelConversationArgs)
	)
	if err = ctx.ShouldBindJSON(args); err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiParamsErr,
			Err:  err,
		})
		return
	}
	db := sdk.DB(ctx)
	conv := new(model.TbConversation)
	if err = db.First(conv, "id = ?", args.ConversationID).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			utils.ERR(ctx, &utils.ErrArgs{
				Code: errs.ApiRecordNotFound,
				Err:  err,
			})
		} else {
			utils.ERR(ctx, &utils.ErrArgs{
				Code: errs.ApiDbErr,
				Err:  err,
			})
		}
		return
	}
	err = db.Transaction(func(tx *gorm.DB) error {
		if conv.ToUID != "" {
			if err := tx.Model(new(model.TbC2cMsgRecord)).Where(
				"((from_uid = ? and to_uid = ?) or (from_uid = ? and to_uid = ?)) and del_uid = ?",
				ctx.GetString(consts.UID), conv.ToUID, conv.ToUID, ctx.GetString(consts.UID), "0").UpdateColumn("del_uid", ctx.GetString(consts.UID)).Error; err != nil {
				return err
			}
			if err := tx.Model(new(model.TbC2cMsgRecord)).Where(
				"((from_uid = ? and to_uid = ?) or (from_uid = ? and to_uid = ?)) and del_uid = ?",
				ctx.GetString(consts.UID), conv.ToUID, conv.ToUID, ctx.GetString(consts.UID), conv.ToUID).UpdateColumn("del_uid", "-1").Error; err != nil {
				return err
			}
			if err := tx.Delete(conv).Error; err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiDbErr,
			Err:  err,
		})
		return
	}
	_ = sdk.AsyncPool().Submit(func() {
		//静默修改推送数量
		ws.UpdateBadge(ctx.GetString(consts.UID))
	})
	utils.SUC(ctx, args.ConversationID)
}
